14. Immutable Objects

Immutable Objects

In this section, we'll briefly cover immutable objects and why they are a good idea, especially in multi-threaded code.

ND079 JPND C2 L05 A15 Immutable Objects

What are Immutable Objects?

An immutable object is an object whose value cannot change after it is created.

The term "immutable" has the same base as the word "mutate". If an object is IM-mutable, that means it cannot be mutated.

Mutable Objects

  • Unsafe to use as hash keys.
  • If used from multiple threads, must be explicitly synchronized.
  • Harder to reason about in code.

Immutable Objects

  • Can be safely used as keys in hash-based data structures, like HashMap.
  • Inherently thread-safe.
  • Easier to reason about in code.

What are some advantages of using immutable objects?

SOLUTION:
  • They are safe to use as keys in hash-based data structures like `HashMap`.
  • Immutable objects can be accessed from multiple threads without any synchronization.
  • Immutable objects are easier to reason about as a programmer, because you don't have to worry about the value changing.